<template>
  <div class="studyed-wrap">
    <div class="chose-course-top">
      <div class="header-left">
        <span class="back-arrow" @click="quitStudy"></span>
      </div>
      <div class="course-title">
        学后检测
      </div>
      <div class="btn-group">
        <a @click="goSkill">考点解读</a>
      </div>
    </div>
    <div class="studyed-section">
      <div class="studyed-inner-wrap">
        <a-tabs v-model="tabKey" type="card"  :forceRender="true">
          <a-tab-pane :key="1" tab="">
            <div class="studyed-content">
              <p>
                <img
                  class="record-icon"
                  src="~assets/reverse/mic1.png"
                  alt=""
                />
                <span class="record-title">复述本句</span>
              </p>
              <div class="step-text">
                <div class="buffer">
                  <!-- <div class="buffer-desc">
                    <div class="buffer-desc-content">{{ voiceResult }}</div>
                  </div> -->
                  <div class="buffer-item">
                    <div class="buffer-item-l">
                      <span v-show="voice >= 1"></span>
                      <span v-show="voice >= 2"></span>
                      <span v-show="voice >= 3"></span>
                      <span v-show="voice >= 4"></span>
                      <span v-show="voice >= 5"></span>
                      <span v-show="voice >= 6"></span>
                      <span v-show="voice >= 7"></span>
                      <span v-show="voice >= 8"></span>
                      <span v-show="voice >= 9"></span>
                      <span v-show="voice >= 10"></span>
                    </div>
                    <div class="buffer-item-r">
                      <span v-show="voice >= 1"></span>
                      <span v-show="voice >= 2"></span>
                      <span v-show="voice >= 3"></span>
                      <span v-show="voice >= 4"></span>
                      <span v-show="voice >= 5"></span>
                      <span v-show="voice >= 6"></span>
                      <span v-show="voice >= 7"></span>
                      <span v-show="voice >= 8"></span>
                      <span v-show="voice >= 9"></span>
                      <span v-show="voice >= 10"></span>
                    </div>
                  </div>
                </div>
              </div>
              <div>
                <a-button type="primary" shape="round" @click="realTimeAsrStop"
                  >完成录音</a-button
                >
              </div>
            </div>
          </a-tab-pane>
          <a-tab-pane :key="2" tab="" :forceRender="true">
            <Finish
              :recordUrl="recordUrl"
              :renderData="sentenceList"
              :sentenceCurrent="sentenceCurrent"
              :tabKey="tabKey"
              :score="score"
              :nextList="nextList"
              @recordAgain="recordAgain"
            ></Finish>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
    <Timetips ref="timetips"></Timetips>
  </div>
</template>
<script>

import { diffStrScore } from "@/utils/tools";
import { grammarSenRatioSub } from "@/services/reverse";
import { uploadAudio } from "@/services/composition.js";
import { mapState, mapMutations } from "vuex";
import Recorder from "recorder-core";
import "recorder-core/src/engine/mp3";
import "recorder-core/src/engine/mp3-engine";
import "recorder-core/src/extensions/waveview";
import { Tabs } from "ant-design-vue";
import Finish from "./finish";
import { SUCCESS_CODE } from "@/utils/const";
import { randomArr } from '@/services/composition.js'
import Timetips from "@/components/Timetips";
export default {
  name: "sceneIndex",
  components: {
    ATabs: Tabs,
    ATabPane: Tabs.TabPane,
    Finish,
    Timetips
  },
  data() {
    return {
      tabKey: 1,
      nextList: {
        test: [],
      },
      asrData: [],
      recIsOpen: false,
      BSync: null,
      isController: false,
      id: "",
      isBuffer: false,
      isVoice: false,
      DB: 0,
      voice: 0,
      socket: null,
      // isFinished: false,
      audio: "",
      recordUrl: "",
      rec: null,
      wave: null,
      recBlob: null,
      recordTransformData: null,
      recordStarted: false,
      voiceResult: "",
      voiceModel: "",
      max_record: 15,
      score: 0, // 分数
    };
  },
  watch: {
    DB(newDb) {
      if (+newDb === 0) {
        this.voice = 0;
      } else if (newDb >= 1 && newDb <= 20) {
        // 显示一格音谱
        this.voice = 1;
      } else if (newDb >= 21 && newDb <= 40) {
        this.voice = 2;
        // 显示二格音谱
      } else if (newDb >= 41 && newDb <= 60) {
        this.voice = 3;
        // 显示三格音谱
      } else if (newDb >= 71 && newDb <= 90) {
        this.c = 4;
        // 显示四格音谱
      } else if (newDb >= 91 && newDb <= 120) {
        this.voice = 5;
        // 显示五格音谱
      } else if (newDb >= 121 && newDb <= 140) {
        this.voice = 6;
        // 显示六格音谱
      } else if (newDb >= 141 && newDb <= 160) {
        this.voice = 7;
        // 显示七格音谱
      } else if (newDb >= 161 && newDb <= 180) {
        this.voice = 8;
        // 显示八格音谱
      } else if (newDb >= 181 && newDb <= 200) {
        this.voice = 9;
        // 显示九格音谱
      } else if (newDb > 200) {
        this.voice = 10;
        // 显示全部音谱
      }
    },
  },
  created() {
    this.BSync = window.isBSync();
    this.isController = window.isController();
    this.realTimeAsrInit();
    // let audio = this.$refs.audio
    // this.audioSrc = 'blob:https://127.0.0.1:8081/7add5434-66a2-4518-b1aa-5a312caf90c9'
    // let that = this;
    // if (!that.isController) {
    //   that.BSync && that.BSync.socket.on("sync:socket", function(data) {
    //     that.socketMessage(data);
    //   });
    // }
  },
  mounted() {},
  beforeDestroy() {
    if (this.rec !== null) {
      this.realTimeAsrStop();
      this.rec = null;
    }
    this.$refs.timetips.stopTimer();
    this.$refs.timetips.stopEndTimer();
  },
  computed: {
    ...mapState({
      reverseStatus: (state) => state.reverseStatus,
      sentenceList: (state) => state.sentenceList,
      sentenceCurrent: (state) => state.sentenceCurrent,
    }),
  },
  methods: {
    ...mapMutations(["setSentenceList", "setGrammarExplain"]),
    randomArr(voiceModel) {
      return randomArr({type: voiceModel})
    },
    recordAgain () {
      this.tabKey = 1
      this.realTimeAsrInit();
    },
    realTimeAsrInit() {
      this.voiceModel = ''
      let that = this;
      !this.rec &&
        (this.rec = Recorder({
          type: "mp3",
          sampleRate: 16000,
          bitRate: 16,
          bufferSize: 4096,
          onProcess: (
            buffers,
            powerLevel,
            bufferDuration,
            bufferSampleRate
          ) => {
            this.recordTransformData = Recorder.SampleData(
              buffers,
              bufferSampleRate,
              16000,
              {
                index: this.recordTransformData
                  ? this.recordTransformData.index
                  : 0,
                offset: this.recordTransformData
                  ? this.recordTransformData.offset
                  : 0.0,
              }
            );
            // 业务处理-start
            let buffer = buffers[buffers.length - 1];
            var maxVal = 0;
            for (var i = 0; i < buffer.length; i++) {
              if (maxVal < buffer[i]) {
                maxVal = buffer[i];
              }
            }
            this.DB = parseInt(maxVal / 100);
            // 业务处理-end
            this.socket.send(this.recordTransformData.data);
            // if (bufferDuration / 1000 > this.min_record) {
            //   this.isStop = false;
            // }
            if (bufferDuration / 1000 >= this.max_record) {
              this.asrSyncStopEvent();
            }
          },
        }));
      if (!that.isController) {
        that.BSync && that.BSync.socket.on("sync:socket", function(data) {
          that.realTimeAsrMessage(data);
        });
        that.BSync && that.BSync.socket.on("sync:cmd", (data) => {
          data.cmd &&
            eval(`typeof ${data.cmd} == 'function' && ${data.cmd}(data)`);
        });
      }
      this.realTimeAsrOpen();
    },
    _realTimeAsrOpen() {
      console.log("正在启动转写");
      let that = this;
      this.socket = new WebSocket(
        `wss://vop.baidu.com/realtime_asr?sn=${new Date().getTime()}`,
        "websocket"
      );
      this.socket.addEventListener("open", () => {
        this.socket.send(
          JSON.stringify({
            type: "START",
            data: {
              appid: 21812587,
              appkey: "WzgLZY1Ico79HSU6fzzsG9Ic",
              dev_pid: 17372,
              cuid: "cuid-1",
              format: "pcm",
              sample: 16000,
            },
          })
        );
        this.DB = 0;
        this.isBuffer = true;
        this.isVoice = false;
        this.isStop = true;
        this.rec.start();
      });
      if (that.isController) {
        this.socket.addEventListener("message", (msgevt) => {
          let data = msgevt.data;
          if (data) {
            data = JSON.parse(data);
            if (data.err_no == 0) {
              that.BSync && that.BSync.socket.emit("sync:socket", data);
              that.realTimeAsrMessage(data);
            }
          }
        });
      }
      this.socket.addEventListener("close", (e) => {
        if (e.target.url === this.socket.url) {
          this.asrSyncStopEvent();
        }
        console.log("关闭连接", e);
      });
    },
    _realTimeAsrMessage(data) {
      // 业务处理
      console.log("业务处理.识别数据", data);
      this.voiceModel = data.join(" ");
      this.voiceResult = data.join(" ");
    },
    realTimeAsrMessage(data) {
      console.log("原始数据", data);
      this.asrData[this.asrData.length == 0 ? 0 : this.asrData.length - 1] =
        data.result;
      if (data.type == "FIN_TEXT") {
        this.asrData[this.asrData.length] = "";
      }
      this._realTimeAsrMessage(this.asrData);
    },
    asrSyncStopEvent() {
      let that = this;
      // 传递关闭事件
      if (that.isController) {
        that.BSync && that.BSync.socket.emit("sync:cmd", {
          cmd: "that.realTimeAsrStop",
        });
        that.realTimeAsrStop();
      }
    },
    realTimeAsrStop() {
      // 加锁
      // if (this.bufferDuration / 1000 < this.min_record && this.isStop) {
      //   this.$toast("录音时间太短哦~");
      //   return;
      // }
      if (this.recordTransformData) {
        this.recordTransformData = null;
        this.asrData = [];
        this.isBuffer = false;
        this.isVoice = true;
        this.voiceResult = "";
        console.log(this.voiceModel);
        this.isComplete = true;
        this.isStop = false;
        console.log(this.rec);
        console.log(this.voiceModel);
        this.rec.stop(async (blob, duration) => {
          console.log(33, blob, duration);
          let syncData = await this.randomArr(this.voiceModel)
          this.voiceModel = syncData.data
          this.$nextTick(async () => {
            this.blob = blob;
            this.score = diffStrScore(
              this.voiceModel,
              this.sentenceList.list.find((v) => v.id === this.sentenceCurrent.id)
                .title
            );
            console.log(this.voiceModel, "???????");
            let formDataBlob = new FormData();
            formDataBlob.append("file", blob, "recorder.mp3");
            formDataBlob.append("type", "grammar");
            await uploadAudio(formDataBlob).then((res) => {
              if (res.code === SUCCESS_CODE) {
                console.log(this, res.data.path)
                this.recordUrl = res.data.path;
              }
            });
            this.subSenRecord();
          })
        });
      }
    },
    realTimeAsrOpen(asr = true) {
      if (this.playing || this.defaultPlaying) {
        this.$toast("请先暂停播放读音");
        return;
      }
      // 加锁
      if (this.recordTransformData) return false;
      console.log("正在打开录音组件");
      if (this.recIsOpen) {
        if (asr) return this._realTimeAsrOpen();
        else return false;
      }
      this.rec.open(
        (success) => {
          console.log("rec.open", success);
          this.recIsOpen = true;
          if (this.recIsOpen) {
            if (asr) return this._realTimeAsrOpen();
            else return false;
          }
        },
        (msg, isUserNotAllow) => {
          //用户拒绝未授权或不支持
          this.$toast((isUserNotAllow ? "UserNotAllow，" : "") + "无法录音:" + msg);
        }
      );
    },
    goSkill() {
      this.setGrammarExplain(true);
    },
    socketMessage(data) {
      console.log(88888, data);
      if (data.err_no == 0) {
        if (this.isController) {
          this.BSync && this.BSync.socket.emit("sync:socket", data);
        }
        this.voiceResult = data.result;
        this.voiceModel += data.result;
      }
    },
    subSenRecord() {
      grammarSenRatioSub({
        chapter_id: this.reverseStatus.chapters_id,
        curr_id: this.reverseStatus.curr_id,
        sen_id: this.sentenceCurrent.id,
        score: this.score + "",
      }).then((res) => {
        if (res.code === SUCCESS_CODE) {
          // 修改 pass 值 同步状态
          let currentIndex = this.sentenceList.list.findIndex(
            (v) => v.id === this.sentenceCurrent.id
          );
          this.sentenceList.list[currentIndex].pass = res.data.pass;
          this.$nextTick(() => {
            this.setSentenceList(this.sentenceList);
          });
          this.nextList = res.data;
          this.tabKey = 2;
        } else {
          // this.$message.error('')
        }
      });
    },
    quitStudy() {
      this.$yxpConfirm({
        msg: "是否退出检测",
      }).then(() => {
        this.$router.push({
          path: "/reverse/grammar-sentence",
        });
      });
    },
  },
};
</script>
<style lang="less" scoped>
/* @import url(); 引入公共css类 */
@import url("./index.less");
</style>
